﻿using AutoMapper;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Project.DTO;
using Project.IService;
using Project.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Project.WebAPI.Controllers
{
    /// <summary>
    /// 产品
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class BeGoodAtController : ControllerBase
    {
        private readonly IBeGoodAtService service;
        private readonly IMapper mapper;
        private readonly IWebHostEnvironment env;

        public BeGoodAtController(IBeGoodAtService service,IMapper mapper, IWebHostEnvironment env)
        {
            this.service = service;
            this.mapper = mapper;
            this.env = env;
        }

        /// <summary>
        /// 设计列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> Get()
        {
           
            var list = await service.GetList().OrderBy(n=>n.OrderBy).Select(n=>new { n.Id,n.Title,n.OrderBy}).ToListAsync();
            return Ok(list);
        }

        /// <summary>
        /// 根据Id获取对象
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public async Task<IActionResult> Get(Guid id)
        {
            var tool = await service.GetList(n => n.Id == id).Select(n => new { n.Id, n.Title, n.OrderBy }).FirstOrDefaultAsync();
            return Ok(tool);
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="tool">工具对象</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Post(BegoodatPost tool)
        {
            var obj = mapper.Map<BeGoodAt>(tool);
            await service.AddAsync(obj);
            return Ok(new { id=obj.Id});
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public IActionResult Delete(Guid id)
        {
            service.MarkRemove(id);

            return Ok("删除完成！");
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="id"></param>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPut("{id}")]
        public async Task<IActionResult> Edit(Guid id, BeGoodatPut dto)
        {
            var bga = await service.GetEntityAsync(n => n.Id == id);
            if (bga.Id != dto.Id)
                return BadRequest("尝试修改他人数据，请求被拒绝！");
            await service.EditAsync(mapper.Map<BeGoodAt>(dto));
            return Ok("修改完成！");

        }

    }
}
